<?php

namespace App\Http\Middleware;

use App\Libraries\Enigma\EnigmaHelper;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ApiDecrypt
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        // 检查请求数据是否存在并且是 JSON 格式
        if ($request->isJson()) {
            // 解密请求数据中的 data 字段
            $requestData = $request->json()->all();

            $item = $requestData[0] ?? '';
            Log::channel('decrypt')->info(json_encode(['item' => $item], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            $data = [];
            if (!empty($item)) {
                $decrypt = EnigmaHelper::decrypt($item);
                $data = json_decode($decrypt, true);
                Log::channel('decrypt')->info(json_encode(['data' => $data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            }
            if (is_array($data)) {
                $request->merge($data);
            }
        }

        return $next($request);
    }
}
